package org.example.designPattern.structural.proxy.dynamicproxy.cglibProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.example.designPattern.structural.proxy.dynamicproxy.jdkProxy.IPerson;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {
    private IPerson person;
    public IPerson getInstance(IPerson person){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(person.getClass());
        enhancer.setCallback(this);
        return (IPerson)enhancer.create();
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if(method.getDeclaringClass().equals(Object.class)){
            return method.invoke(o, objects);
        }

        beforeProcess();
        Object invoke = methodProxy.invokeSuper(o, objects);
        afterProcess();
        return invoke;
    }

    private void beforeProcess(){
        System.out.println("欢迎来到非诚勿扰，说出你的要求：");
    }

    private void afterProcess(){
        System.out.println("配对成功开始交往");
    }
}
